function plot_modelfit(project, i, model, showsilhouette)

% PLOT_MODELFIT  Plots the fit of the model for instance 'i'.
%   
%   To view the initial fit before optimization, do not pass 'model'.

if nargin < 4
    showsilhouette = true;
end

if showsilhouette
    plot_silhouette(project, i);
end

P = size(project.vertices, 1);
if nargin < 3
    verts      = project.vertices;
    rotscale   = eye(4);
    translate  = eye(4);
else
    n          = model(1);
    M          = model(2);
    S          = model(3:2 + n);
    
    vs         = 5 * sum(S(1:i - 1)) + (i - 1) * (7 + M) + n + 2;
    tvs        = vs + 5 * S(i) + 1;
    tve        = vs + 5 * S(i) + 7;
    mvs        = vs + 5 * S(i) + 8;
    mve        = vs + 5 * S(i) + 7 + M;
    v          = model(tvs:tvs + 2);
    rotscale   = [ model(tve) .* expm([    0 -v(3)  v(2) ;
                                        v(3)     0 -v(1) ;
                                       -v(2)  v(1)     0 ]) zeros(3, 1) ;
                                                            zeros(1, 3) 1];
    translate  = [ 1 0 0 model(tvs + 3) ;
                   0 1 0 model(tvs + 4) ;
                   0 0 1 model(tvs + 5) ;
                   0 0 0 1              ];
    
    shapemodes = reshape(model(end - 3 * P * (M + 1) + 1:end), ...
                         3 * P, M + 1);
    verts      = reshape(shapemodes * [1 ; model(mvs:mve)], ...
                         P, 3);
end


DT          = translate * ...
              project.images(i).transform * rotscale;
transformed = [ verts ones(P, 1) ] * DT';
plot_looplimit(project.mesh, transformed(:, 1:3));

end

